package com.tanhua.dubbo.server.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.tanhua.dubbo.server.exception.UnauthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * * @title: RequestService
 *
 * @Author Philcan
 * @Date: 2021/8/15 18:25
 * @Version 1.0
 */
@Service
@Slf4j
public class RequestService {
    @Autowired
    private TokenService tokenService;

    @Retryable(value = UnauthorizedException.class, maxAttempts = 5, backoff = @Backoff(delay = 2000L, multiplier = 2))
    public HttpResponse execute(String url, String body, Method method) {
        String token = this.tokenService.getToken();
        HttpRequest httpRequest;
        switch (method) {
            case GET: {
                httpRequest = HttpRequest.get(url);
                break;
            }
            case POST: {
                httpRequest = HttpRequest.post(url);
                break;
            }
            case DELETE: {
                httpRequest = HttpRequest.delete(url);
                break;
            }
            case PUT: {
                httpRequest = HttpRequest.put(url);
                break;
            }
            default: {
                return null;
            }
        }
        HttpResponse response = httpRequest.header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + token)
                .body(body).timeout(20000).execute();
        if (response.getStatus() == 401) {
            this.tokenService.refreshToken();
            throw new UnauthorizedException(url, body, method);
        }
        return response;
    }

    @Recover
    public HttpResponse recover(UnauthorizedException e) {
        log.error("获取token失败!url=" + e.getUrl() + ",body=" + e.getBody() + ",method=" + e.getMethod());
        return null;
    }
}
